package com.xm.limiter;

/**
 * 漏桶算法
 */
public class LeakyBucketLimiter04 implements Limiter {
    private final int capacity; // 桶容量
    private final double rate; // 流出速率（个/毫秒）
    private int water; // 当前水量
    private long lastTime = System.currentTimeMillis();

    /**
     * 漏桶算法：需要严格限制调用速率的场景（如第三方API调用）
     * @param capacity 桶容量
     * @param rate 流出速率（个/毫秒）
     */
    public LeakyBucketLimiter04(int capacity, double rate) {
        this.capacity = capacity;
        this.rate = rate;
    }

    @Override
    public synchronized boolean tryAcquire() {
        long now = System.currentTimeMillis();
        long elapsed = now - lastTime;
        water = (int) Math.max(0, water - elapsed * rate);
        lastTime = now;
        if (water < capacity) {
            water++;
            return true;
        }
        return false;
    }
}